package com.imoresoft.magic.action;

import java.util.HashMap;
import java.util.Map;

import com.ambitor.grass.sql.dao.SuperDao;
import com.ambitor.grass.sql.dao.impl.SuperDaoImpl;
import com.ambitor.grass.util.data.DataMap;
import com.ambitor.grass.util.data.DatasetList;
import com.ambitor.grass.util.data.IData;
import com.ambitor.grass.util.data.IDataset;
import com.imoresoft.magic.parser.templet.IUserTempletParser;
import com.imoresoft.magic.parser.templet.UserTempletParserFactory;
import com.imoresoft.magic.top.TopConstants;
import com.imoresoft.magic.top.TopService;

public class PreviewAction extends BaseAction {

	private static final long serialVersionUID = -1641837048613839690L;

	TopService topService = new TopService(TopConstants.EVN_SWITCH,
			TopConstants.APP_KEY, TopConstants.APP_SECRET);

	private transient Map<String, String> userTemplet = new HashMap<String, String>();

	private transient String title = "为您精心挑选的宝贝";

	private transient int numPerTr = 4;

	private transient String itemsStr = new String();

	private transient String ruleType = null;

	private String result = "";

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public String getItemsStr() {
		return itemsStr;
	}

	public void setItemsStr(String itemsStr) {
		this.itemsStr = itemsStr;
	}

	public String getRuleType() {
		return ruleType;
	}

	public void setRuleType(String ruleType) {
		this.ruleType = ruleType;
	}

	public Map<String, String> getUserTemplet() {
		return userTemplet;
	}

	public void setUserTemplet(Map<String, String> userTemplet) {
		this.userTemplet = userTemplet;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public int getNumPerTr() {
		return numPerTr;
	}

	public void setNumPerTr(int numPerTr) {
		this.numPerTr = numPerTr;
	}

	@SuppressWarnings("unchecked")
	public String preview() throws Exception {
		IData userTempletStyle = new DataMap(userTemplet);

		IDataset itemList = new DatasetList(this.getItemsStr());
		if ("TF_M_USER_RULE_RANDOM".equals(ruleType)) {
			itemList = topService.getRandomItems(pd.getTopSessionId(), pd
					.getTopNick(), numPerTr);
		}

		String moduleHtml = "";
		try {
			SuperDao superDao = new SuperDaoImpl(pd.getConn());

			IUserTempletParser userTempletParser = UserTempletParserFactory
					.instance(superDao, userTempletStyle, itemList,
							new DataMap(), title, numPerTr);
			moduleHtml = userTempletParser.buildDisplayHtml();
		} catch (Exception e) {
			moduleHtml = "<div>发生错误，请联系管理员</div>";
			logger.error("", e);
		}
		this.setResult(moduleHtml);

		if (numPerTr == 4) {
			return "160";
		} else if (numPerTr == 5) {
			return "120";
		}
		return SUCCESS;
	}

}
